<template>
  <div class="gray-page resident-detail-page">
    <nav-bar title="领导任务" theme="white"></nav-bar>
    <div class="page-main">
      <van-sticky class="page-scroll" :offset-top="44">
        <van-form
          ref="from"
          :show-error="false"
          input-align="right"
          error-message-align="right"
          validate-trigger="onSubmit"
          :label-width="120"
          @submit="onSubmit"
          @failed="onFailed"
        >
          <van-field
            required
            name="taskName"
            v-model="formParams.taskName"
            label="任务名称"
            placeholder="请输入"
            right-icon="arrow"
            class="van-field__right-icon-white"
            :maxlength="50"
            :rules="rules.taskName"
          />
          <van-field
            required
            name="taskDescribe"
            :rules="rules.taskDescribe"
            v-model="formParams.taskDescribe"
            rows="4"
            autosize
            label="任务描述"
            type="textarea"
            maxlength="500"
            placeholder="请输入描述......"
            show-word-limit
          />
          <van-field label="添加图片/视频" readonly :border="false">
            <template #input>
              <van-radio-group v-model="accept" direction="horizontal">
                <van-radio name="image/*">图片</van-radio>
                <van-radio name="video/*">视频</van-radio>
              </van-radio-group>
            </template>
          </van-field>
          <van-field class="van-field__value--upload" input-align="left">
            <template #input>
              <van-uploader
                name="fileList"
                v-model="fileList"
                :accept="accept"
                max-count="9"
                :max-size="maxSize"
                :before-read="uploadBeforeRead"
                :after-read="uploadAfterRead"
                @click-preview="previewClick"
              >
                <template #preview-cover="file">
                  <div v-if="format.includes(file.file.name.split('.')[file.file.name.split('.').length - 1])">
                    <div class="van-uploader__preview-masker"></div>
                    <video-player
                      class="video-player vjs-custom-skin"
                      :playsinline="true"
                      :options="{
                        aspectRatio: '16:16',
                        sources: [
                          {
                            src: $config.ImageURl + file.file.url
                          }
                        ]
                      }"
                    ></video-player>
                  </div>
                </template>
                <div class="van-uploader__input--white">
                  <div class="van-uploader__input--content">
                    <div class="upload-image">
                      <img src="@/assets/images/basic/icon_camera@2x.png" />
                    </div>
                    <div class="upload-text">点击拍摄</div>
                  </div>
                </div>
              </van-uploader>
            </template>
          </van-field>
          <van-field
            required
            readonly
            clickable
            name="deadline"
            v-model="formParams.deadline"
            label="截止时间"
            placeholder="请输入"
            right-icon="arrow"
            :rules="rules.deadline"
            @click="dateOpenPopup('deadline')"
          />
          <van-field
            required
            name="degreeConcernName"
            v-model="formParams.degreeConcernName"
            label="优先级"
            placeholder="请选择"
            right-icon="arrow"
            :rules="rules.degreeConcern"
            @click="dictOpenPopup('degreeConcern')"
          />
          <div style="padding: 16px">
            <van-button block type="info" native-type="submit">确定</van-button>
          </div>
        </van-form>
      </van-sticky>
    </div>
    <!-- 字典项 -->
    <van-popup v-model="dictPopupShow" round position="bottom" @close="dictValue = ''">
      <van-picker
        show-toolbar
        :default-index="dictData[dictType] && dictData[dictType].findIndex(o => o.code === dictValue)"
        :columns="dictData[dictType]"
        value-key="description"
        @cancel="dictPopupShow = false"
        @confirm="dictOnConfirm"
      />
    </van-popup>
    <!-- 日期 -->
    <van-popup v-model="datePopupShow" round position="bottom" @close="date = new Date()">
      <van-datetime-picker
        v-model="date"
        type="datetime"
        title="选择年月日"
        :min-date="minDate"
        :max-date="maxDate"
        @cancel="datePopupShow = false"
        @confirm="dateTimeOnConfirm"
      />
    </van-popup>
    <!-- 视频预览 -->
    <gb-video :url="videoUrl" :show.sync="videoPopupShow"></gb-video>
  </div>
</template>

<script>
import Upload from '@/mixins/upload'
import { FormParams } from './libs/data'
import SelectPopup from '@/mixins/selectPopup'
import Routine from '@/api/routine'
export default {
  mixins: [Upload, SelectPopup],
  data() {
    return {
      formParams: new FormParams(),
      buttonDisabled: false,
      folder: 'task',
      accept: 'image/*',
      maxSize: 50 * 1024 * 1024,
      format: ['mp4', 'avi', 'mov'],
      fileList: [],
      videoUrl: '',
      videoPopupShow: false,
      rules: {
        taskName: [{ required: true, message: '请填写任务名称', trigger: 'blur' }],
        taskDescribe: [{ required: true, message: '请填写任务描述', trigger: 'blur' }],
        deadline: [{ required: true, message: '请选择截止时间', trigger: 'change' }],
        taskPriorityName: [{ required: true, message: '请选择优先级', trigger: 'change' }]
      },
      dictTypes: 'degreeConcern,taskStatus',
      dateTimeShow: false,
      currentDate: new Date()
    }
  },
  mounted() {
    this.getDict(this.dictTypes)
  },
  methods: {
    // 视频预览
    previewClick({ file }, detail) {
      const urlArr = this.fileList[detail.index].url.split('.')
      const suffix = urlArr[urlArr.length - 1]
      if (this.format.includes(suffix)) {
        this.videoPopupShow = true
        this.videoUrl = this.$config.ImageURl + this.fileList[detail.index].url
      }
    },
    // 校验失败
    onFailed(errorInfo) {
      this.$refs.from.scrollToField(errorInfo.errors[0].name)
    },
    formatDate(date) {
      var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
      var dates = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
      var hour = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
      var minute = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
      return `${date.getFullYear()}-${month}-${dates} ${hour}:${minute}`
    },
    dateTimeOnConfirm(date) {
      this.datePopupShow = false
      this.formParams.deadline = this.formatDate(date)
    },
    onSubmit() {
      this.buttonDisabled = true
      this.formParams.taskPicture = this.fileList.map(o => o.url).join(',')
      this.formParams.taskPriority = this.formParams.degreeConcern
      this.formParams.taskStatus = '1'
      this.formParams.taskReceiver = this.$route.query.gridPersonCode
      console.log(JSON.stringify(this.formParams))
      Routine.Task.taskSave(this.formParams)
        .then(res => {
          const { status } = res.data
          if (status === 0) {
            this.buttonDisabled = false
            this.$router.push({
              path: '/page/message',
              query: {
                backTo: '-2',
                title: '提交成功'
              }
            })
          } else {
            this.buttonDisabled = false
            this.$toast.fail(res.data.message)
          }
        })
        .catch(() => {
          this.buttonDisabled = false
        })
    }
  }
}
</script>

<style></style>
